class Post < ActiveRecord::Base
  belongs_to :board
  belongs_to :owner, :class_name => "User", :foreign_key => "user_id"
  
  validates_presence_of :content
  validates_presence_of :owner
  validates_presence_of :board #, :if => Proc.new {|p| p.is_root}
  validates_presence_of :title, :if => Proc.new {|p| p.is_root}
  
  acts_as_tree :order => 'created_at'
  
  def is_root
    parent == nil
  end
  
  def discussion_size
    children.inject(1) do |sum, ch|
      sum + ch.discussion_size
    end
  end
  
  def createAnswer(arguments)
    ans = Post.new(arguments.merge(:board_id=>board_id))
    children << ans
  end
  
  before_save do |post|
    # post.board = nil unless post.is_root
    post.children.each do |p| 
      p.update_attribute(:board, post.board)
    end
  end
  
end
